package com.recipes.meg;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class Create extends Activity {
	// Initialize variables to hold sqlite database and database helper
	SQLiteDatabase db;
	DatabaseHelper db_helper;
	
	// Initialize array to hold ingredient inputs
	ArrayList<EditText> ingredients = new ArrayList<EditText>();
	
	// Initialize array to hold ingredients prompts
	ArrayList<TextView> ing_prompts = new ArrayList<TextView>();
	
	// Initialize array to hold rows
	ArrayList<TableRow> rows = new ArrayList<TableRow>();
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        
        // Initialize new database helper variable
        db_helper = new DatabaseHelper(this);
        
        // Initialize first row, input box and prompt and add them to respective arrays
        rows.add((TableRow)findViewById(R.id.tableRow1));
        ingredients.add((EditText)findViewById(R.id.first_ing_in));
        ing_prompts.add((TextView)findViewById(R.id.first_ing_prompt));
        
        // Get table layout to put ingredients in
        final TableLayout ing_layout = (TableLayout) findViewById(R.id.ing_table);
        
        // Iterate to add next 4 ingredient prompts and inputs
        for(int i = 1; i < 5; i++){
        	// Create a new row for the table
        	TableRow temp_row = new TableRow(this);
        	
        	// Create a TextView to be the prompt for this ingredient
        	TextView temp_prompt = new TextView(this);
        	
        	// Set the color of this prompt to be blue
        	temp_prompt.setTextColor(getResources().getColor(R.color.blue));
        	
        	// Set the size of this prompt to be 15sp
        	temp_prompt.setTextSize(15);
        	
        	// Format a string to be the text of this prompt which includes its number
        	String temp_text = String.format("Ingredient %d", i+1);
        	
        	// Set the text of this prompt to be the above string
        	temp_prompt.setText(temp_text);
        	
        	// Declare the parameters to be used for this prompt
        	TableRow.LayoutParams temp_params1 = new TableRow.LayoutParams(
        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        	
        	// Set the left margin of this prompt to be 5
        	temp_params1.leftMargin = 5;
        	
        	// Set the weight of this prompt to be 0.2
        	temp_params1.weight = (float) 0.2;
        	
        	// Add temp_prompt to this row
        	temp_row.addView(temp_prompt, temp_params1);
        	
        	// Add temp_prompt to ing_prompts array
        	ing_prompts.add(temp_prompt);
        	
        	// Create EditText field
        	EditText temp_in = new EditText(this);

        	// Set this EditText field to capitalize the first letter of each word and use built in suggestion
        	temp_in.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_CLASS_TEXT);
        	
        	// Declare the parameters to be used for this input box
        	TableRow.LayoutParams temp_params2 = new TableRow.LayoutParams(
        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        	
        	// Set the right and bottom margins of this input box to be 5
        	temp_params2.setMargins(0, 0, 5, 5);
        	
        	// Set the weight of this input box to be 0.8
        	temp_params2.weight = (float) 0.8;
        	
        	// Add temp_in to the row
        	temp_row.addView(temp_in, temp_params2);
        	
        	// Add temp_in to ingredients array
        	ingredients.add(temp_in);
        	
        	// Add temp_row to the table layout
        	ing_layout.addView(temp_row, new TableLayout.LayoutParams(
        			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        	
        	// Add temp_row to the rows array
        	rows.add(temp_row);
        }
        
        // Initialize button to add ingredients
        Button add = (Button) findViewById(R.id.add_ing);
        
        // Set onClickListener for add
        add.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Create a new row for the table
	        	TableRow temp_row = new TableRow(getApplicationContext());
	        	
	        	// Create a TextView to be the prompt for this ingredient
	        	TextView temp_prompt = new TextView(getApplicationContext());
	        	
	        	// Set the color of this prompt to be blue
	        	temp_prompt.setTextColor(getResources().getColor(R.color.blue));
	        	
	        	// Set the size of this prompt to be 15sp
	        	temp_prompt.setTextSize(15);
	        	
	        	// Format a string to be the text of this prompt which includes its number
	        	String temp_text = String.format("Ingredient %d", ingredients.size()+1);
	        	
	        	// Set the text of this prompt to be the above string
	        	temp_prompt.setText(temp_text);
	        	
	        	// Declare the parameters to be used for this prompt
	        	TableRow.LayoutParams temp_params1 = new TableRow.LayoutParams(
	        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        	
	        	// Set the left margin of this prompt to be 5
	        	temp_params1.leftMargin = 5;
	        	
	        	// Set the weight of this prompt to be 0.2
	        	temp_params1.weight = (float) 0.2;
	        	
	        	// Add temp_prompt to this row
	        	temp_row.addView(temp_prompt, temp_params1);
	        	
	        	// Add temp_prompt to ing_prompts array
	        	ing_prompts.add(temp_prompt);
	        	
	        	// Create EditText field
	        	EditText temp_in = new EditText(getApplicationContext());
	        
            // Set this EditText field to capitalize the first letter of each word and use built in suggestion
            temp_in.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_CLASS_TEXT);
        	
	        	// Declare the parameters to be used for this input box
	        	TableRow.LayoutParams temp_params2 = new TableRow.LayoutParams(
	        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        	
	        	// Set the right and bottom margins of this input box to be 5
	        	temp_params2.setMargins(0, 0, 5, 5);
	        	
	        	// Set the weight of this input box to be 0.8
	        	temp_params2.weight = (float) 0.8;
	        	
	        	// Add temp_in to the row
	        	temp_row.addView(temp_in, temp_params2);
	        	
	        	// Add temp_in to ingredients array
	        	ingredients.add(temp_in);
	        	
	        	// Add temp_row to the table layout
	        	ing_layout.addView(temp_row, new TableLayout.LayoutParams(
	        			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	        	
	        	// Add temp_row to the rows array
	        	rows.add(temp_row);
			}
		});
        
        // Initialize button to delete ingredients
        Button delete = (Button) findViewById(R.id.delete_ing);
        
        // Set onClickListener for delete
        delete.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Make sure number of rows is greater than 1
				if(rows.size() > 1){
					// Get last row from rows array
					TableRow temp_row = rows.get(rows.size()-1);

					// Remove all views from this row
					temp_row.removeAllViews();

					// Remove this row from TableLayout
					ing_layout.removeView(temp_row);

					// Remove last ingredient from ingredients array
					ingredients.remove(ingredients.size()-1);

					// Remove last prompt from ing_prompts array
					ing_prompts.remove(ing_prompts.size()-1);

					// Remove last row from rows array
					rows.remove(rows.get(rows.size()-1));
				}
			}
		});
        
        // Initialize button to move to next screen and save current results
        Button next = (Button) findViewById(R.id.next);
        
        // Set onClickListener for next
        next.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Instantiate EditText field for name
				EditText name_in = (EditText) findViewById(R.id.name_in);
				
				// Get contents of name_in
				String name = name_in.getText().toString();
				
				// Check if name is not blank
				if(name.equalsIgnoreCase("")){
					// If it is then give an error message and return prematurely
					Toast.makeText(getApplicationContext(), "Recipe must have a name", Toast.LENGTH_SHORT).show();
					return;
				}
				
				// Open database for reading
				db = db_helper.getWritableDatabase();
				
				// Check if this name is a duplicate in the database pass -1 as id of this
					// row to make sure that this new recipe does not match any recipes already
					// in database
				int result = db_helper.duplicateName(db, name, -1);
				
				// Close the database
				db.close();
				
				// Check if this returned non-zero
				if(result != 0){
					// If so then check if result is positive
					if(result > 0){
						// If it is then give an error message
						Toast.makeText(getApplicationContext(), "Recipe must have a unique name", Toast.LENGTH_SHORT).show();
					}
					
					// Return prematurely
					return;
				}

				// Initialize a hashtable to store contents of ingredients input boxes
				Hashtable<String, Integer> ing_hashes = new Hashtable();
				
				// Initialize arraylist to hold input names of ingredients
				ArrayList<String> names = new ArrayList<String>();
				
				// Iterate through ingredients array
				for(int i = 0; i < ingredients.size(); i++){
					// Get the contents of this ingredients input box
					String ing = ingredients.get(i).getText().toString();

					// Make sure this input is not blank
					if(ing.equalsIgnoreCase("")){
						// If it is then give an error message and return prematurely
						Toast.makeText(getApplicationContext(), "Recipe cannot have blank ingredients", Toast.LENGTH_SHORT).show();
						return;
					}
					
					// Check if the all lowercase version of ing has already been used 
						// as a key for ing_hashes
					Integer exists = 0;
					exists = ing_hashes.get(ing.toLowerCase());
					
					// Check if this hash lookup returned non-null
					if(exists != null){
						// If so then give an error message and return prematurely
						Toast.makeText(getApplicationContext(), "Recipe must have unique ingredients", Toast.LENGTH_SHORT).show();
						return;
					}
					
					// Otherwise it did return null
					else{
						// If so then put a 1 into ing_hashes using the all lowercase version
							// of ing as its key
						ing_hashes.put(ing.toLowerCase(), 1);
					}
					
					// Put the text in this input box into the names array
					names.add(ing);
				}

				// Open database for reading and writing
				db = db_helper.getWritableDatabase();
				
				// Call function to insert new recipe into database
				int id = db_helper.create(db, name, names);
				
				// Close the database
				db.close();
				
				// Check if insertion failed
				if(id == -1){
					// If this returned negative give an error message and return prematurely
					Toast.makeText(getApplicationContext(), "Recipe was not created", Toast.LENGTH_SHORT).show();
					return;
				}
				
				// Initialize intent to start Create2 activity
				Intent start_create2 = new Intent(getApplicationContext(), Create2.class);

				// Put id of new recipe into intent as an extra
				start_create2.putExtra("id", id);
				
				// Start start_create2 intent
				startActivity(start_create2);

				// Upon return to this activity finish it
				finish();
			}
		});
    }
}
